# Copyright (c) 2023 Presto Labs Pte. Ltd.
# Author: taekwon

import fire
import json
import requests
import time

# TODO(taekwon): removed this file after wliang's PI work.
def run(initialize=False):
  obj = dict()
  origin_categories = list()
  category_filepath = "data/coin2/quant/coin_category.json"
  binance_swap_pi_filepath = "data/coin2/product_info/Futures.Binance.v1.json"
  native_symbol_map = dict()
  with open(binance_swap_pi_filepath, "r") as fin:
    pi_list = json.load(fin)['product_infos']
    for single_pi in pi_list:
      native_symbol_map[single_pi['native_symbol']] = single_pi

  ban_categories = ['BUSD']
  if not initialize:
    print("Get original categories order..")
    with open(category_filepath, "r") as fin:
      origin_categories = json.load(fin)['categories']
    print("origin categories: ", origin_categories)
  # parsing
  content = requests.get("https://fapi.binance.com/fapi/v1/exchangeInfo").json()
  for one_pi in content['symbols']:
    if one_pi['status'] != 'TRADING' or one_pi['symbol'] not in native_symbol_map.keys():
      continue
    base_asset = native_symbol_map[one_pi['symbol']]['base']
    for cate in one_pi['underlyingSubType']:
      if cate in ban_categories:
        continue
      elif not cate in obj:
        obj[cate] = set()
      obj[cate].update({base_asset})
  for k, v in obj.items():
    obj[k] = sorted(list(v))
  # add new category
  new_categories = list(obj.keys())
  added_categories = set(new_categories) - set(origin_categories)
  new_categories = origin_categories + list(added_categories)
  print("new added: ", added_categories)
  format_obj = {'fetched_timestamp': time.time_ns(), 'categories': new_categories, 'infos': obj}
  print(format_obj)
  json.dump(format_obj, open(category_filepath, 'w'), indent=2)


if __name__ == "__main__":
  fire.Fire(run)
